package com.liangsui.mss.srevice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liangsui.mss.constants.Constants;
import com.liangsui.mss.constants.MQConstants;
import com.liangsui.mss.domain.CareHistory;
import com.liangsui.mss.domain.CareOrderItem;
import com.liangsui.mss.domain.OrderCharge;
import com.liangsui.mss.domain.OrderChargeItem;
import com.liangsui.mss.dto.*;
import com.liangsui.mss.mapper.CareHistoryMapper;
import com.liangsui.mss.mapper.CareOrderItemMapper;
import com.liangsui.mss.mapper.OrderChargeItemMapper;
import com.liangsui.mss.mapper.OrderChargeMapper;
import com.liangsui.mss.mq.dto.BaseMqDto;
import com.liangsui.mss.mq.service.RocketMqService;
import com.liangsui.mss.service.OrderChargeService;
import com.liangsui.mss.vo.DataGridView;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
* @author zhang
* @description 针对表【his_order_charge(收费表)】的数据库操作Service实现
* @createDate 2022-12-06 22:36:39
*/
@DubboService(methods = {@Method(name="saveOrderAndItems",retries = 0)}, timeout = 20000)
public class OrderChargeServiceImpl extends ServiceImpl<OrderChargeMapper, OrderCharge>
    implements OrderChargeService{
    /**
     * @功能描述:操作订单--收费
     * @Description:
     */
    @Autowired
    private OrderChargeMapper orderChargeMapper;

    /**
     * @功能描述:操作订单-支付订单详情
     * @Description:
     */
    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    /**
     * @功能描述:操作处方详情
     * @Description:
     */
    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private RocketMqService rocketMqService;

    /**
     * 保存收费订单和详情信息
     *
     * @param orderChargeFromDto
     * @功能描述:组装前端过来的数据，保存收费订单及详情 (不是支付成功 ， 而是保存当前订单信息)
     * @Description: orderChargeFromDto 《收费和详情数据》
     */
    @Override
    public void saveOrderAndItems(OrderChargeFromDto orderChargeFromDto) {
        /***************************************保存收费订单信息开始***********************************************/
        OrderChargeDto orderChargeDto = orderChargeFromDto.getOrderChargeDto();
        List<OrderChargeItemDto> orderChargeItemDtoList = orderChargeFromDto.getOrderChargeItemDtoList();
        // 保存
        OrderCharge charge = new OrderCharge();
        BeanUtil.copyProperties(orderChargeDto, charge);
        // 设置支付状态
        charge.setOrderStatus(Constants.ORDER_STATUS_0);
        charge.setCreateBy(orderChargeFromDto.getSimpleUser().getUserName());
        charge.setCreateTime(DateUtil.date());
        charge.setPatientName(orderChargeFromDto.getOrderChargeDto().getPatientName());
        this.orderChargeMapper.insert(charge);
        /***************************************保存收费订单信息结束***********************************************/

        /***************************************保存支付订单信息详情开始***********************************************/
        for (OrderChargeItemDto orderChargeItemDto : orderChargeItemDtoList) {
            OrderChargeItem orderChargeItem = new OrderChargeItem();
            BeanUtil.copyProperties(orderChargeItemDto, orderChargeItem);
            // 设置关联处方订单ID
            orderChargeItem.setOrderId(charge.getOrderId());
            // 设置未收费
            orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_0);
            this.orderChargeItemMapper.insert(orderChargeItem);
        }
        /***************************************保存支付订单信息详情结束***********************************************/
        if (Constants.PAY_TYPE_0.equals(orderChargeDto.getPayType())) {
            //do nothing
        } else {
            rocketMqService.sendDelay(MQConstants.Topic.CANCEL_PAY_ORDER,
                    new CancelOrderMqDto(new CancelPayOrderDto(charge.getOrderId()), UUID.randomUUID().toString()),
                    MQConstants.DelayLevel.level_6);
        }
    }

    /**
     * 支付宝成功回调，这里是PayController来调用修改订单状态
     *
     * @param orderId       支付订单ID
     * @param payPlatformId 第三方平台支付ID  如果是现金，则为空
     * @功能描述:支付成功之后更新订单状态
     * @Description:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(String orderId, String payPlatformId) {
        try {
            /*****************更改支付(收费)订单状态开始*********************/
            // 根据支付订单ID 查询 支付订单信息(收费)
            OrderCharge charge = this.orderChargeMapper.selectById(orderId);
            // 设置平台交易编号(支付宝) 如果是现金则为空
            charge.setPayPlatformId(payPlatformId);
            // 更改订单支付状态 (已支付)
            charge.setOrderStatus(Constants.ORDER_STATUS_1);
            // 设置支付时间
            charge.setPayTime(DateUtil.date());
            charge.setUpdateTime(DateUtil.date());
            // 设置患者名称
            CareHistory careHistory = this.careHistoryMapper.selectById(charge.getChId());
            charge.setPatientName(careHistory.getPatientName());
            // 更新订单信息
            this.orderChargeMapper.updateById(charge);
            /*****************更改支付(收费)订单状态结束*********************/

            /*****************更新支付成功的项目的状态为(已支付)*********************/
            // 根据支付订单号查询支付订单详情
            QueryWrapper<OrderChargeItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OrderChargeItem.COL_ORDER_ID, orderId);
            List<OrderChargeItem> orderChargeItemList = this.orderChargeItemMapper.selectList(queryWrapper);
            // 遍历取出详情ID (用来更新支付详情状态)
            ArrayList<String> itemIdList = new ArrayList<>();
            // 修改代码风格Stream链式编程
            orderChargeItemList.stream().forEach(e -> itemIdList.add(e.getItemId()));

            // 更新支付详情状态
            OrderChargeItem orderChargeItem = new OrderChargeItem();
            orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_1);
            // 定制条件
            QueryWrapper<OrderChargeItem> orderChargeItemQueryWrapper = new QueryWrapper<>();
            orderChargeItemQueryWrapper.in(OrderChargeItem.COL_ITEM_ID, itemIdList);
            this.orderChargeItemMapper.update(orderChargeItem, orderChargeItemQueryWrapper);

            // 更新处方详情
            CareOrderItem careItemObj = new CareOrderItem();
            careItemObj.setStatus(Constants.ORDER_DETAILS_STATUS_1);
            // 定制条件
            QueryWrapper<CareOrderItem> careItemQw = new QueryWrapper<>();
            careItemQw.in(CareOrderItem.COL_ITEM_ID, itemIdList);
            this.careOrderItemMapper.update(careItemObj, careItemQw);
            /*****************更新支付成功的项目的状态为(已支付)结束*********************/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @param orderId 订单ID
     * @功能描述:根据订单ID查询订单信息【验证是否支付成功】
     */
    @Override
    public OrderCharge queryOrderChargeByOrderId(String orderId) {
        return this.orderChargeMapper.selectById(orderId);
    }

    /**
     * @param orderChargeDto
     * @功能描述:分页查询所有收费单
     * @Description:
     */
    @Override
    public DataGridView queryAllOrderChargeForPage(OrderChargeDto orderChargeDto) {
        Page<OrderCharge> page = new Page<>(orderChargeDto.getPageNum(), orderChargeDto.getPageSize());
        QueryWrapper<OrderCharge> orderChargeQueryWrapper = new QueryWrapper<>();
        orderChargeQueryWrapper.like(StringUtils.isNotBlank(orderChargeDto.getPatientName()), OrderCharge.COL_PATIENT_NAME, orderChargeDto.getPatientName());
        orderChargeQueryWrapper.like(StringUtils.isNotBlank(orderChargeDto.getRegId()), OrderCharge.COL_REG_ID, orderChargeDto.getRegId());
        orderChargeQueryWrapper.orderByDesc(OrderCharge.COL_CREATE_TIME);
        this.orderChargeMapper.selectPage(page, orderChargeQueryWrapper);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    /**
     * @param orderId
     * @功能描述:根据收费单的ID查询收费详情信息(收费的处方详细信息)
     * @Description:查看详情根据订单ID
     */
    @Override
    public List<OrderChargeItem> queryOrderChargeItemByOrderId(String orderId) {
        QueryWrapper<OrderChargeItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq(OrderChargeItem.COL_ORDER_ID, orderId);
        List<OrderChargeItem> orderChargeItemList = this.orderChargeItemMapper.selectList(itemQueryWrapper);
        return orderChargeItemList;
    }

    @Override
    public OrderChargeItem queryOrderChargeItemByItemId(String itemId) {
        return orderChargeItemMapper.selectById(itemId);
    }

    /**
     * 订单支付超时
     * @param orderId
     */
    @Override
    public void cancelPayOrder(String orderId) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq(OrderCharge.COL_ORDER_ID, orderId);
        updateWrapper.set(OrderCharge.COL_ORDER_STATUS, Constants.ORDER_STATUS_2);
        orderChargeMapper.update(null, updateWrapper);
    }
}




